package com.zoespeer.food_delivery_comment_api.interceptor;

import com.alibaba.fastjson.JSON;
import com.zoespeer.food_delivery_comment_api.common.ApiResponse;
import com.zoespeer.food_delivery_comment_api.util.TokenParseUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; // 1. 确保 import
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
@Component
/**
 * Token验证拦截器：拦截需要登录的接口，验证Token有效性及是否在黑名单中
 */
public class LoginInterceptor implements HandlerInterceptor {

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public LoginInterceptor(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        String authorization = request.getHeader("Authorization");

        // 2. 验证Token格式
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 2. (修改点) 添加 401 状态码
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(ApiResponse.error("401:Token格式错误，需以Bearer 开头")));
            writer.flush();
            writer.close();
            return false;
        }

        String token = authorization.substring(7).trim();

        // 4. 检查黑名单
        String blacklistKey = "token:blacklist:" + token;
        if (redisTemplate.hasKey(blacklistKey)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 3. (修改点) 添加 401 状态码
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(ApiResponse.error("401:Token已失效（已退出登录）")));
            writer.flush();
            writer.close();
            return false;
        }

        // 5. 验证Token有效性
        ApiResponse<String> parseResult = TokenParseUtil.parseUserIdAsString(authorization);
        if (!parseResult.isSuccess()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 4. (修改点) 添加 401 状态码
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(ApiResponse.error("401:" + parseResult.getMessage())));
            writer.flush();
            writer.close();
            return false;
        }

        // 5. (关键修复)
        // 你之前在这里添加的 if (parseResult.isSuccess()) { ... return false; }
        // 必须被删除！

        // 6. Token有效且未被拉黑，放行请求
        return true;
    }
}